import { defineStore } from 'pinia'

import { ref, computed } from 'vue'
import { getCurrentDate, initList } from '@/utils'

export const useCalendarStore = defineStore('calendar', () => {
  // 当前的日期
  const currentDate = getCurrentDate() // 当前日期 {year: 2024, month: 12, date: 27}

  // 选择的日期, 使用当前日期作为初始值
  const selectedDate = ref(currentDate)

  // 选中的年份
  const year = computed({
    get: () => selectedDate.value.year,
    set: (value) => {
      selectedDate.value.year = value
    },
  })

  // 选中的月份
  const month = computed({
    get: () => selectedDate.value.month,
    set: (value) => {
      selectedDate.value.month = value
    },
  })

  // 选中的日期
  const date = computed({
    get: () => selectedDate.value.date,
    set: (value) => {
      selectedDate.value.date = value
    },
  })

  const lists = computed(() => {
    return initList(year.value, month.value)
  })

  const formatDate = computed(() => {
    return `${year.value}-${month.value}-${date.value}`
  })

  const lastMonth = () => {
    month.value--
    if (month.value < 1) {
      month.value = 12
      year.value--
    }
  }

  const nextMonth = () => {
    month.value++
    if (month.value > 12) {
      month.value = 1
      year.value++
    }
  }

  const backToToday = () => {
    selectedDate.value = getCurrentDate()
  }

  return {
    year,
    month,
    date,
    lists,
    formatDate,
    lastMonth,
    nextMonth,
    backToToday,
  }
})
